package de.wittekind.bundesjugendspiele.basics;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class Config {

	private String path;
	private Properties properties;

	public Config(String path) throws IOException {
		this.path = path;
		if (!isExisting()) {
			createFile();
		}
		load();
	}

	public boolean isExisting() {
		return !(new File(path).length() == 0);
	}

	private void load() throws IOException {
		properties = new Properties();
		BufferedInputStream stream = new BufferedInputStream(
				new FileInputStream(path));
		properties.load(stream);
		stream.close();
	}

	protected String getString(String key) {
		if (properties.containsKey(key))
			return properties.getProperty(key);
		System.err.println("Key nicht gefunden");
		return null;
	}

	protected void setString(String key, String value) {
		properties.put(key, value);
		storeProperties();
	}

	protected void setInteger(String key, Integer value) {
		properties.put(key, value.toString());
		storeProperties();
	}

	protected int getInteger(String key) throws NumberFormatException {
		String s = getString(key);
		return new Integer(s);
	}

	private void createFile() throws IOException {
		File f = new File(path);
		f.getParentFile().mkdirs();
		f.createNewFile();
	}

	private void storeProperties() {
		try {
			BufferedOutputStream stream = new BufferedOutputStream(
					new FileOutputStream(path));
			properties.store(stream, "Generated by Diem");
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
